// 引入express服务器
const express = require('express');
const pool = require('../pool');
//引入token模块
const jwt = require("../jwt.js")
// 创建路由器对象
const user = express.Router();
// 验证码
// user.get('/othercode', (req, res) => {
//   req.session._id = data._id.toString();
// 	//第一个版本:图形类型的验证码
// 	// const cap = svgCaptcha.create({
// 	// 		// 翻转颜色
// 	// 		inverse: false,
// 	// 		// 字体大小
// 	// 		fontSize: 36,
// 	// 		// 噪声线条数/干扰线
// 	// 		noise: 3,
// 	// 		// 宽度
// 	// 		width: 80,
// 	// 		// 高度
// 	// 		height: 30,
// 	// 		//是否是彩色
// 	// 		color:true,
// 	// 		ignoreChars:"0o1i",
// 	// 		size:4,//验证码长度
// 	// 	});

// 	//第二个版本:算术计算
// 	// http://127.0.0.1:3000/pro2/v1/code
// 	// const cap = svgCaptcha.createMathExpr({
// 	// 	fontSize: 45,
// 	// 	mathMin: 1,
// 	// 	mathMax: 9,
// 	// 	mathOperator: "+-",
// 	// 	width: 110,
// 	// 	height: 45,
// 	// 	color: true,
// 	// })
// 	req.session.captcha = cap.text; // session 存储验证码数值！！！！！
// 	//console.log(req.session)
// 	res.type('svg'); // 响应的类型
// 	res.send(cap.data)
// });
// ----------------1.用户登录------------------
// post
user.post("/login", (req, res, next) => {
  var obj = req.body;
  let reg1 = /^[1][3-8]\d{9}$/;//验证identifier格式为手机号
  let reg2 = /^\w+([-+.]\w+)@\w+([-.]\w+).\w+([-.]\w+)*$/;//验证邮箱
  let r1 = reg1.test(obj.identifier);
  let r2 = reg2.test(obj.identifier);
  let sql = '';
  if (r1) {
    sql = "SELECT * FROM lpk_user WHERE (phone=? AND lpwd=?)";
  } else if (r2) {
    sql = "SELECT * FROM lpk_user WHERE (email=? AND lpwd=?)";
  } else {
    sql = "SELECT * FROM lpk_user WHERE (username=? AND lpwd=?)"
  }
  pool.query(sql, [obj.identifier, obj.lpwd], (err, result) => {
    if (err) {
      next(err);
      return;
    } else if (result.length == 0) {//没找到数据
      res.send({
        code: 201,
        msg: '用户不存在，请重新输入'
      });
    } else {
      res.send({
        code: 200,
        msg: '登录成功',
        data: result[0],
        token: jwt.generateToken(result[0])//登录成功后，将用户对象放在token中存放在sessionStorage中
      });
    }
  });
})
// 检测用户名是否存在
user.post("/un", (req, res, next) => {
  var obj = req.body;
  console.log(obj)
  var sql = "SELECT * FROM lpk_user  where username=?";
  pool.query(sql, [obj.username], (err, result) => {
    if (err) {
      next(err);
      return
    } else if (result.length > 0) {
      res.send({
        code: 201,
        msg: '用户名已被占用',
      });
    } else {
      res.send({
        code: 200,
        msg: '用户名可用',
      });
    }
  });
})
// 检测手机号是否存在
user.post("/up", (req, res, next) => {
  var obj = req.body;
  console.log(obj)
  var sql = "SELECT * FROM lpk_user  where phone=?";
  pool.query(sql, [obj.phone], (err, result) => {
    if (err) {
      next(err);
      return;
    } else if (result.length > 0) {
      res.send({
        code: 201,
        msg: '手机号已注册',
      });
    } else {
      res.send({
        code: 200,
        msg: '手机号可用',
      });
    }
  });
})
// 获取验证码请求，需要随机生成数字
user.post('/getcode', (req, res) => {
  // 生成数字，存入session
  let code = Math.floor(Math.random() * 9000 + 1000);
  console.log('getCode:' + code);
  req.session.code = code;
  console.log(req.session);
  res.send({
    code: 200,
    msg: '已获取验证',
    data: req.session.code,
  });
})
// ------2 注册----------
user.post("/register", (req, res, next) => {
  var obj = req.body;
  // console.log('session'+req.session)
  // let code = req.session.code;
  // console.log(code);
  // if (code !== obj.code) {
  //   res.send({
  //     code: 201,
  //     msg: '验证码错误'
  //   })
  // } else {
  let sql = "INSERT INTO lpk_user (username,phone,lpwd,avatar) VALUES (?,?,?,?)";
  pool.query(sql, [obj.username, obj.phone, obj.lpwd, obj.avatar], (err, result) => {
    if (err) {
      next(err);
      return;
    }
    res.send({
      code: 200,
      msg: '注册成功'
    })
  })
  // }
})

// -------------------3.用户更新信息---------------------
user.post("/update", (req, res, next) => {
  var obj = req.body;
  let sql = "UPDATE lpk_user SET username=?,email=?,user_sex=?,user_birth=? WHERE lid=?";
  pool.query(sql, [obj.username, obj.email, obj.user_sex, obj.user_birth, obj.lid], (err, result) => {
    if (err) {
      next(err);
      return;
    }
    res.send({
      code: 200,
      msg: '更新成功'
    })
  })
})
// 更新用户余额
user.post("/wallet", (req, res, next) => {
  var obj = req.body;
  let sql = "UPDATE lpk_user SET wallet=? WHERE lid=?";
  pool.query(sql, [obj.wallet, obj.lid], (err, result) => {
    if (err) {
      next(err);
      return;
    }
    res.send({
      code: 200,
      msg: '余额更新成功'
    })
  })
})

// -------------------3.查询用户信息---------------------
user.post("/details", (req, res, next) => {
  var obj = req.body;
  console.log(obj);
  let sql = "SELECT * FROM lpk_user WHERE lid=?";
  pool.query(sql, [obj.lid], (err, result) => {
    if (err) {
      next(err);
      return;
    }
    if (result.length == 0) {
      res.send({
        code: 201,
        msg: '查询失败'
      })
    } else {
      res.send({
        code: 200,
        msg: '查询成功',
        data: result
      })
    }
  })
})
// 加入用户购物车
user.post("/putin", (req, res, next) => {
  var obj = req.body;
  console.log(obj);
  let sql = "INSERT INTO user_cart (user_id,goods_id,price,count) VALUES (?,?,?,?)";
  pool.query(sql, [obj.user_id, obj.goods_id, obj.price, obj.count], (err, result) => {
    if (err) {
      next(err);
      return;
    }
    if (result.length == 0) {
      res.send({
        code: 201,
        msg: '添加失败'
      })
    } else {
      res.send({
        code: 200,
        msg: '添加成功',
        data: result
      })
    }
  })
})
// 查询用户购物车
user.post("/cart", (req, res, next) => {
  var obj = req.body;
  console.log(obj);
  let sql = 'SELECT user_cart.*,lpk_goods.* FROM (user_cart INNER JOIN lpk_user ON user_cart.user_id=lpk_user.lid) INNER JOIN lpk_goods ON user_cart.goods_id=lpk_goods.gid WHERE lid=?';
  pool.query(sql, [obj.lid], (err, result) => {
    if (err) {
      next(err);
      return;
    }
    console.log(result)
    if (result.length == 0) {
      res.send({
        code: 201,
        msg: '查询失败'
      })
    } else {
      res.send({
        code: 200,
        msg: '查询成功',
        data: result
      })
    }
  })
})
// 删除用户购物车商品
user.delete("/putoff", (req, res, next) => {
  var obj = req.query;
  console.log(obj);
  let sql = 'DELETE FROM user_cart  WHERE goods_id=? AND user_id=?';
  pool.query(sql, [obj.goods_id, obj.user_id], (err, result) => {
    if (err) {
      next(err);
      return;
    }
    console.log(result)
    if (result.affectedRows == 0) {
      res.send({
        code: 201,
        msg: '删除失败'
      })
    } else {
      res.send({
        code: 200,
        msg: '删除成功',
      })
    }
  })
})
// 导出路由器对象
module.exports = user;